require "net/http"
require "json"

module Trifle
	module Ruby
		class Handler
			def self.submit!(type, json_data)
				return unless Config.load
				thread = Thread.new do
					config = Config.load[::Rails.env || ENV["rack_env"] || ENV["RAILS_ENV"]]
					begin
						ziped_data = Zlib::Deflate.deflate( json_data, Zlib::BEST_SPEED )
						uri = URI.parse( "#{ config[ "secure" ] ? "https" : "http" }://#{ config[ "host" ] }:#{ config[ "port" ] }/#{ type }" )
						http = Net::HTTP.new( uri.host, uri.port )
						if config[ "secure" ]
							http.use_ssl = true
							http.verify_mode = OpenSSL::SSL::VERIFY_NONE
						end
						req = Net::HTTP::Post.new( uri.path )
						req.body = {
							api_key: config[ "api_key" ],
							name: "trifle-ruby",
							version: "#{Trifle::Ruby::VERSION}",
							data: Base64.encode64( ziped_data )
						}.to_json
						req[ "Accept" ] = "application/vnd.trifle.v2"
						req[ "Content-Type" ] = "application/json"
						Logger.info http.request( req ).body
					rescue => e
						Logger.error "Unable to push data: #{e}"
					end
				end
			end
		end
	end
end
